package com.share.algorithm.stack;

/**
 * @desc:基于数组的栈
 * @author:caifan
 * @date:2020/6/14
 */
public class ArrayStack implements MyStack<Integer> {

    private Integer [] data = new Integer[5];
    private int index = 0;//数组位置

    public ArrayStack(int cap) {
        data = new Integer[cap];
    }

    /**
     * 出栈
     */
    @Override
    public void pop() {
        judgeSize();
        data[index--] = null;
    }

    /**
     * 入栈
     * @param o
     */
    @Override
    public void push(Integer o) {
        judgeSize();
        data[index++] = o;
    }

    @Override
    public void judgeSize() {
        if (data.length >= index) {
            resize(data.length * 2);
        } else if (index > 0 && index < data.length / 2) {
            resize(data.length / 2);
        }
    }

    /**
     * 数组复制进行容量调整
     * @param size
     */
    @Override
    public void resize(int size) {
        Integer[] temp = new Integer[size];
        for (int i=0;i<size;i++) {
            temp[i] = data[i];
        }
        data = temp;
    }

    @Override
    public int size() {
        return index;
    }

    @Override
    public boolean isEmpty() {
        if (data.length == 0) {
            return true;
        }
        return false;
    }
}
